package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElasticsearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrResponseVo;
import com.atguigu.gulimall.search.vo.BrandVo;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.swing.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author gcq
 * @Create 2020-12-28
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParam param) {

        // 查询返回结果
        SearchResult result = null;

        // 1、动态构建出查询需要的SQL语句
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            // 2、执行检索请求
            SearchResponse response = client.search(searchRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
            // 3、分析响应数据并进行处理返回我们需要的格式
            result = buildSearchResult(response, param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建结果数据,es搜索命中的结果
     *
     * @param response
     * @param param
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        // 1、准备返回结果
        SearchResult result = new SearchResult();
        // 2、拿到搜索命中结果
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();
        // 3、验证结果是否不为空
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                // 4、文档来源字符串
                String sourceAsString = hit.getSourceAsString();
                // 5、转成skuesmodel对象
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                // 6、全文匹配关键字不为空，设置高亮结果
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    // 7、拿到突出显示的片段
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                esModels.add(skuEsModel);
            }
        }
        // 8、拿到商品数据
        result.setProducts(esModels);

        // 9、拿到商品设计到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 9.1、得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            // 9.2、得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            // 9.3、得到属性的所有值
            List<String> attrValue = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            // 9.4、设置到对象中
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValue);

            result.getAttrIds().add(attrId);
            // 9.5、添加到集合中
            attrVos.add(attrVo);
        }
        // 9.6、设置到Vo中
        result.setAttrs(attrVos);

        // 10、当前所有商品的分类信息
        ParsedLongTerms Catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = Catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            // 10.1、拿到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            // 10.2、拿到分类名称
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            // 10.4、添加到分类集合中
            catalogVos.add(catalogVo);
        }
        // 10.5、商品分类信息添加到Vo中
        result.setCatalogs(catalogVos);

        // 11、当前所有商品的品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 11.1、拿到品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            // 11.2、拿到品牌的名称
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            // 11.3、拿到品牌的图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            // 11.4、将品牌数据设置到对象中
            brandVo.setBrandImg(brandImg);
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            // 11.5、将品牌数据保存到集合中
            brandVos.add(brandVo);
        }
        // 11.6、商品品牌信息添加到Vo中
        result.setBrands(brandVos);

        // 12、分页信息 -总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        // 12.1、分页信息 - 页码
        result.setPageNum(param.getPageNum());
        // 12.2、分页信息 - 总页码
        int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : ((int) total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(totalPages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        // 13、构建面包屑导航
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> navVoList = param.getAttrs().stream().map(attr -> {
                // 13.1、分析每个attrs传递过来的值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                // 13.2、attrs=2.5寸：6寸
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                // 13.3、根据attrid远程查询到属性信息
                R r = productFeignService.getAttrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    // 13.4、设置面包屑名称
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }
                // 取消这个面包屑导航以后，我们要跳转到那个地方，将请求地址的url里面的当前置空
                //拿到所有的查询条件后，去掉当前
                // attrs=15_海思(Hisilicon)
                String replace = replaceQueryString(param, attr, "attrs");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());
            // 13.5、将面包屑导航数据放到Vo中
            result.setNavs(navVoList);
        }

        // 14、商品的品牌和分类
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            // 14.1、远程查询所有品牌
            R info = productFeignService.getBrandById(param.getBrandId());
            if (info.getCode() == 0) {
                List<BrandVo> brand = info.getData("brand", new TypeReference<List<BrandVo>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String release = "";
                for (BrandVo brandVo : brand) {
                    // 14.2、拿到品牌名称
                    buffer.append(brandVo.getBrandName() + ";");
                    // 14.3、进行替换
                    release = replaceQueryString(param,brandVo.getBrandId() + "", "brandId");
                }
                // 14.4、设置到面包屑对象中
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.gulimall.com/list.html?" + release);
            }
            // 14.5、添加到集合中
            navs.add(navVo);
        }

        return result;
    }

    private String replaceQueryString(SearchParam param, String value,String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+","%20");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param.get_queryString().replace("&" + key + "=" + encode, "");
    }
    private SearchRequest buildSearchRequest(SearchParam param) {
        // 1、构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        /**
         * 模糊匹配 过滤 (按照属性、分类、品牌、价格区间、库存)
         */
        // 2、构建bool-query
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();
        // 2.1、must - 模糊匹配全文匹配关键字
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }

        // 2.2 bool - filter 按照分类id来进行查询
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }

        // 2.3 bool - filter 按照品牌id进行查询
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }

        // 2.4 bool - filter 按照所有指定的属性来进行查询
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            for (String attr : param.getAttrs()) {
                // 2.4.1、 attr参数数据为:attr=1_5寸:8寸&attrs=2_16G:8G
                // 2.4.2 bool - query
                BoolQueryBuilder nestedboolQuery = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                // 检索属性id
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                // 2.4.2 按照属性和值进行查询
                nestedboolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedboolQuery.must(QueryBuilders.termQuery("attrs.attrValue", attrValues));
                // 2.4.3、每一次查询都生成一个nested查询
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", nestedboolQuery, ScoreMode.None);
                boolQuery.filter(nestedQueryBuilder);
            }
        }

        // 2.5 bool - filter 按照库存进行查询
        boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1 ? true : false));

        // 2.6 bool - filter 按照价格范围进行查询 前端参数传递值为 = 1_500/_500/500_
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            /**
             * gt: greater than 大于
             *
             * gte: greater than or equal 大于等于
             *
             * lt: less than 小于
             *
             * lte: less than or equal 小于等于
             */
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                // 2.6.2、大于等于s[0] 小于等于s[1]
                rangeQueryBuilder.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                // 2.6.3、以下划线开头,按照小于等于查询
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQueryBuilder.lte(s[0]);
                }
                // 2.6.4、以下划线结尾,按照大于等于
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQueryBuilder.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQueryBuilder);
        }

        // 2.7 前面所有条件进行封装
        sourceBuilder.query(boolQuery);

        /**
         * 排序、分页、高亮
         */
        // 3.1 排序
        if (!StringUtils.isEmpty(param.getSort())) {
            String sort = param.getSort();
            /**
             * sort=hotScore_asc/desc
             */
            String[] s = sort.split("_");
            // 3.1.1 升序&降序
            SortOrder sortOrders = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], sortOrders);
        }

        // 3.2、分页 pageSize:5
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        // 3.3、高亮 根据关键字进行高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }
        /**
         * 聚合分析
         */
        // 4.1、品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        // 4.2、品牌子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(2));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(2));
        // 4.3、聚合品牌
        sourceBuilder.aggregation(brand_agg);

        // 4.4、分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        // 4.5、聚合分类
        sourceBuilder.aggregation(catalog_agg);

        // 4.5、属性聚合 attr_agg
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        // 4.6、聚合当前所有attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        // 4.7、聚合分析出当前attr_id对应的名字
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        // 4.8、聚合分析出当前attr_id可能对应的属性值
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        // 4.9、聚合属性
        sourceBuilder.aggregation(attr_agg);

        String s = sourceBuilder.toString();
        System.out.println("构建的DLS：" + s);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
}